package org.example.protocol;

import org.apache.commons.io.IOUtils;
import org.example.common.Invocation;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class HttpClient {

    public String send(String hostname, Integer port, Invocation invocation){
        //用户的配置
        try {
            URL url = new URL("http", hostname, port, "/");
            HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
            httpURLconnection.setRequestMethod("POST");
            httpURLconnection.setDoOutput(true);

            OutputStream outputStream = httpURLconnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);
            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream inputStream = httpURLconnection.getInputStream();
            String result = IOUtils.toString(inputStream);

            return result;
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
